﻿using Common;
using FanYi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace FanYi
{
    public partial class Form1 : Form
    {
        private int currentIndex;
        private readonly BaiduFanYi _fanyi = new BaiduFanYi(Config.AppId, Config.Key, Config.From, Config.To, Config.Delay);
        private readonly Rootobject _rootobject;


        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            LoadFilePath(Config.CurrentPath);
            ShowProgress(Config.CurrentIndex);


            string _path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "regex.json");
            if (File.Exists(_path))
            {
                var json = File.ReadAllText(_path);
                _rootobject = JsonConvert.DeserializeObject<Rootobject>(json);
            }

        }


        /// <summary>
        /// 显示进度
        /// </summary>
        /// <param name="current"></param>
        public void ShowProgress(int current)
        {
            currentIndex = current;
            lab_Total.Text = $"{current}/{lbx_FIleAllPath.Items.Count}";
        }

        /// <summary>
        /// 加载所有文件
        /// </summary>
        /// <param name="path"></param>
        public void LoadFilePath(string path)
        {
            txt_FIlePath.Text = path;
            lbx_FIleAllPath.DataSource = RecursionFiles(path);
        }

        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_FolderBrowser_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                //更新配置文件
                Config.CurrentPath = dialog.SelectedPath;
                Config.CurrentIndex = 0;
                //加载文件
                LoadFilePath(dialog.SelectedPath);
                ShowProgress(0);
            }
        }

        /// <summary>
        /// 递归获取所有文件
        /// </summary>
        /// <returns></returns>
        private List<string> RecursionFiles(string path)
        {
            try
            {
                DirectoryInfo folder = new DirectoryInfo(path);
                var files = folder.GetFiles()
                    .Where(t => !t.Name.StartsWith(".") && !string.IsNullOrWhiteSpace(t.Extension) && Config.FileExtension.Contains(t.Extension))
                    .Select(t => t.FullName)
                    .ToList();

                foreach (var item in folder.GetDirectories().Where(t => !t.Name.StartsWith(".")))
                {
                    files.AddRange(RecursionFiles(item.FullName));
                }
                return files;
            }
            catch (Exception)
            {
                return new List<string> { $"{path} 路径错误！" };
            }

        }

        /// <summary>
        /// 开始翻译
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Render_Click(object sender, EventArgs e)
        {
            btn_Render.Enabled = false;
            btn_FolderBrowser.Enabled = false;


            Task.Run(() =>
            {
                var dataSource = lbx_FIleAllPath.DataSource as List<string>;

                for (int i = Config.CurrentIndex; i < dataSource.Count; i++)
                {
                    var input = File.ReadAllText(dataSource[i].ToString());
                    List<string> keys = new List<string>();

                    input = Regex.Match(input, _rootobject.Content).Value;

                    foreach (var _regex in _rootobject.Replaces)
                    {
                        foreach (Match item in Regex.Matches(input, _regex.Pattern))
                        {
                            keys.Add(item.Groups["value"].Value);
                        }
                        input = Regex.Replace(input, _regex.Pattern, _regex.Replacement);
                    }

                    //翻译所有key
                    foreach (var key in keys)
                    {
                        var text = _fanyi.Render(key);

                        input = input.Replace($"<fanyi>{key}</fanyi>", text);
                    }

                    File.WriteAllText(dataSource[i].ToString(), input);

                    //更新配置信息
                    ShowProgress(i + 1);
                    lbx_Completed.Items.Add(dataSource[i].ToString());
                }

                currentIndex = 0;
                Config.CurrentIndex = 0;
                btn_Render.Enabled = true;
                btn_FolderBrowser.Enabled = true;
            });
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Config.CurrentIndex = currentIndex;
            _fanyi.Save();
        }
    }
}
